package mytask.dao;

import java.util.ArrayList;
import java.util.List;

import mytask.model.Project;
import mytask.model.ProjectMember;
import mytask.model.User;
import mytask.model.UserRole;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Property;
import org.springframework.stereotype.Repository;

@Repository(value = "memberDAO")
public class ProjectMemberDAOImpl extends GeneralDAO implements ProjectMemberDAO {

	@Override
	public void saveProjectMember(ProjectMember member) {
		getHibernateTemplate().saveOrUpdate(member);
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<ProjectMember> listProjectMembers() {
		return getHibernateTemplate().find("from ProjectMember");
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<ProjectMember> listProjectMembers(final User user) {
		final DetachedCriteria criteria = DetachedCriteria.forClass(ProjectMember.class).add(
				Property.forName("user").eq(user));
		return getHibernateTemplate().findByCriteria(criteria);
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<ProjectMember> listProjectMembers(final Project project) {
		final DetachedCriteria criteria = DetachedCriteria.forClass(ProjectMember.class).add(
				Property.forName("project").eq(project));
		return getHibernateTemplate().findByCriteria(criteria);
	}

	@Override
	public ProjectMember getProjectMember(final User user, final Project project) {

		// TODO: ASENDADA ANDMEBAASI TASANDI P2RINGUGA!
		List<ProjectMember> byprojects = listProjectMembers(project);
		for (int i = 0; i < byprojects.size(); i++) {
			if ((byprojects.get(i)).getUser().getId().equals(user.getId())) {
				return byprojects.get(i);
			}
		}
		return null;
	}

	@Override
	public List<ProjectMember> listProjectMembers(final User user, final UserRole role) {
		List<ProjectMember> members = new ArrayList<ProjectMember>();
		List<ProjectMember> byuser = listProjectMembers(user);
		for (int i = 0; i < byuser.size(); i++) {
			if (byuser.get(i).getRole().equals(role)) {
				members.add(byuser.get(i));
			}
		}
		return members;
	}

	@Override
	public ProjectMember getProjectMember(long id) {
		return getHibernateTemplate().get(ProjectMember.class, id);
	}

}